local blaze = require "blaze"
local app = require "app"

local M = {}

M.state = {
    -- 当前的下注档位
    selected_bet_index = 1,

    -- 没有经过等级限制过滤的下注档位
    unfiltered_bet_amounts = {},

    -- 下注档位
    bet_amounts = {},

    -- 赔付线
    pay_lines = {},

    -- 卷轴信息 {{id, symbols}}
    reels = {},

    -- 自动下注
    auto = false,

    -- 自动下注 间隔时间s
    interval_time = 1.5,

    free_times = 0
}

M.getters = {
    bet_value = function(state)
        local value = state.bet_amounts[state.selected_bet_index]
        if value == nil then
            value = 0
        end
        return value
    end,

    is_max_bet = function(state)
        return state.selected_bet_index >= #state.bet_amounts
    end
}

local function pow(x, y)
    if y == 0 then
        return 1
    end

    local t = 1
    while y > 0 do
        t = t * x
        y = y - 1
    end

    return t
end

local function parse_payline(payline, count)
    local ret = {}

    for i = count-1, 0, -1 do
        local t = pow(10, i)
        local x = math.floor(payline/t)
        table.insert(ret, x)
        payline = payline - x*t
    end

    return ret
end

M.mutations = {
    on_free_times = function(store, state, times)
        state.free_times = times
        store.emit("更新免费次数")
    end,

    refilter_bet_amounts = function(store, state, args)
        state.bet_amounts = app.config.bet.filter_amounts(state.unfiltered_bet_amounts)
        state.selected_bet_index = math.min(#state.bet_amounts, state.selected_bet_index)
        store.emit("更新下注档位")
    end,

    on_bet_amounts = function(store, state, args)
        state.unfiltered_bet_amounts = args.bet_amounts
        state.bet_amounts = app.config.bet.filter_amounts(args.bet_amounts)
        state.selected_bet_index = math.min(#state.bet_amounts, state.selected_bet_index)
        store.emit("更新下注档位")
    end,

    on_paylines = function(store, state, args)
        state.pay_lines = args.paylines
        store.emit("更新赔付线")
    end,

    on_reels = function(store, state, args)
        state.reels = args.reels
        store.emit("更新卷轴信息")
    end,

    on_spin_result = function(store, state, result_info)
        store.emit("旋转结果", result_info)
    end,

    -- 升高下注档位
    increase_bet = function(store, state, args)
        local index = math.min(#state.bet_amounts, state.selected_bet_index + 1)
        state.selected_bet_index = index
        store.emit("改变下注")
    end,

    -- 降低下注档位
    decrease_bet = function(store, state, args)
        local index = math.max(1, state.selected_bet_index - 1)
        state.selected_bet_index = index
        store.emit("改变下注")
    end,

    max_bet = function(store, state, args)
        state.selected_bet_index = #state.bet_amounts
        store.emit("改变下注")
    end,

    on_auto = function(store, state, b)
        state.auto = b
        store.emit("改变下注状态")
    end
}

return M